/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Space, Popconfirm } from 'antd';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import KbWhiteListModal from '@/components/_pages/jdk/shield/components/KbWhiteListModal';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { getAddressOptions } from '../../addLeague/_utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import type { WHITELIST_COLUMNS } from '@/components/_pages/jdk/index.d';
import {
  getWhiteList,
  removeWhiteList,
  createWhiteListDelivery,
  modifyWhiteListDelivery,
} from '@/services/jdk/shield';
import { whiteListColumns } from '@/components/_pages/jdk/index.config';
import { useSelector } from 'umi';
import styles from './index.less';
import { isArray } from 'lodash';

const Index = ({ show }: { show: boolean }) => {
  const actionRef = useRef<ActionType>();
  const proFormRef = useRef<ProFormInstance>();
  const [record, setRecord] = useState<any>({});
  const [formData, setFormData] = useState<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const onClose = () => {
    setVisible(false);
    setRecord({});
  };
  const handelAddLeague = () => setVisible(true);
  const handleOption = (record_: any) => {
    const { area_code_list: area, area_name_list } = record_;
    setRecord({ area, agent_area: getAddressOptions({ area, area_name_list }), ...record_ });
    handelAddLeague();
  };

  const onProFormSubmit = async (values: any) => {
    setFormData(values);
    actionRef.current?.reload(true);
  };
  const handleRemove = (record_: any) => {
    const { id } = record_;
    removeWhiteList({ id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        actionRef.current?.reload(true);
      } else {
        message.error(msg);
      }
    });
  };
  const onSubmit = async (values: any) => {
    let api = createWhiteListDelivery;
    if (record && record.id) {
      const { id, brand, phone } = record;
      values = {
        ...values,
        phone,
        brand,
        id,
      };
      api = modifyWhiteListDelivery;
    }
    const { area, agent_area } = values;
    const alist = agent_area || area;
    if (alist) {
      values.area = alist.map((item: any) => {
        return isArray(item) ? item : `${item.value ? item.value : item}`.split(',');
      });
    }
    delete values.agent_area;
    api(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        actionRef.current?.reload();
        message.success(msg);
        onClose();
      } else {
        message.error(msg);
      }
    });
  };

  const optionColumns: ProColumns<WHITELIST_COLUMNS>[] = [
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 80 : 120,
      align: 'center',
      fixed: 'right',
      render: (_, item) => {
        const { league_id } = item;
        return (
          <Space direction='vertical'>
            {!league_id && Number(league_id) <= 0 && (
              <a onClick={handleOption.bind(null, item)}>修改</a>
            )}
            <Popconfirm title='你确定删除吗？' onConfirm={handleRemove.bind(null, item)}>
              <a>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const queryTable = async (values: any) => {
    const { current: page, pageSize } = values;
    const { code, data, msg } = await getWhiteList({ page, size: pageSize, ...formData });
    if (code == 0) {
      return {
        data: data.list || [],
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  useEffect(() => {
    if (show) {
      actionRef.current?.reload();
    }
  }, [show]);
  return (
    <div className={styles.main}>
      <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
        <ProForm
          formRef={proFormRef}
          layout='inline'
          onFinish={onProFormSubmit}
          initialValues={{
            department: '1',
            type: 'name',
          }}
          submitter={{
            render: (form_props) => {
              return [
                <Button
                  key='reset'
                  onClick={() => {
                    form_props.form?.resetFields();
                    form_props.form?.submit?.();
                  }}
                >
                  重置
                </Button>,
                <Button type='primary' key='submit' onClick={() => form_props.form?.submit?.()}>
                  查询
                </Button>,
                <Button key='add' type='primary' onClick={handelAddLeague}>
                  添加
                </Button>,
              ];
            },
          }}
        >
          <ProFormText
            fieldProps={{
              style: { width: '220px' },
            }}
            name='phone'
            placeholder='请输入商家账号查询'
          />
        </ProForm>
      </Space>
      <DragTable>
        <ProTable
          rowKey='league_id'
          actionRef={actionRef}
          request={queryTable}
          columns={[...whiteListColumns, ...optionColumns]}
          toolBarRender={false}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          search={false}
          scroll={{
            x: 1200,
          }}
        />
        <KbWhiteListModal visible={visible} onSubmit={onSubmit} record={record} onClose={onClose} />
      </DragTable>
    </div>
  );
};

export default Index;
